package handle

import (
	"encoding/json"
	"fmt"
	"gitee.com/git_public/vfaith/builtin/vault"
	"html/template"
	"log"
	"net/http"
	"path/filepath"
)

//region 文本信息返回

func ReturnError(handler IxHandler, errInfo string) {
	w := handler.GetWriter()
	http.Error(w, fmt.Sprintf("Internal Server Error：【%s】", errInfo), http.StatusInternalServerError)
}

func ReturnText(handler IxHandler, text string) {
	w := handler.GetWriter()
	w.Header().Set("Content-Type", "text/html; charset=utf-8")
	_, _ = fmt.Fprintf(w, text)
}

func ReturnHTML(handler IxHandler, html string) {
	w := handler.GetWriter()
	w.Header().Set("Content-Type", "text/html; charset=utf-8")
	_, _ = fmt.Fprintf(w, "<!DOCTYPE html><html><head><title>JSON Output</title></head><body>%s</body></html>", html)
}

//endregion

// region ListDataHandle

func ReturnListData(handler IxHandler, data vault.IxBundleData, param ...string) error {
	//List呈现方式：ViewPage、Json、Excel
	//Model呈现方式：ViewPage、EditPage、Json、Excel

	if len(param) > 0 {
		if param[0] == "excel" {
			//返回excel文件
			//ReturnExcel(w, data)
		} else {
			//返回模板页面
			ReturnPage(handler, data, param[0])
		}
	} else {
		//返回JSON数据
		ReturnJson(handler, data)
	}

	return nil
}

func ReturnJson(handler IxHandler, data any) {
	w := handler.GetWriter()

	// 打印结果
	//for _, row := range data.Rows {
	//	fmt.Println(row)
	//}

	// 设置响应头
	w.Header().Set("Content-Type", "application/json")

	// 返回 JSON 响应
	if err := json.NewEncoder(w).Encode(data); err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
	}
}

func ReturnPage(handler IxHandler, data any, tmplPath string) {
	w := handler.GetWriter()

	// 打印结果
	//for _, row := range data.Rows {
	//	fmt.Println(row)
	//}

	newTmpl, err := template.New(filepath.Base(tmplPath)).Funcs(GetTemplateFunc()).ParseFiles(tmplPath)
	if err != nil {
		http.Error(w, "Internal Server Error", http.StatusInternalServerError)
		log.Println(err)
		return
	}

	err = newTmpl.Execute(w, data)
	if err != nil {
		http.Error(w, "Internal Server Error", http.StatusInternalServerError)
		log.Println(err)
	}
}

/*func ReturnExcel(w http.ResponseWriter, data vault.IxBundleData) {
	f, _ := excelv.ExportExcel(data)

	// 设置HTTP头
	w.Header().Set("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
	w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=%s.xlsx", f.GetSheetName(0)))

	_ = f.SetSheetName("Sheet1", "output")

	// 将Excel文件写入HTTP响应
	if err := f.Write(w); err != nil {
		http.Error(w, "Failed to write excel file", http.StatusInternalServerError)
		return
	}

	log.Println("Excel file successfully created and sent!")
}*/

// endregion
